package thread;

import java.util.Random;

/**
 * 线程创建
 * 1.继承Thread类，重写run方法
 *2.实现Runnable接口
 * 启动线程
 *1.调用线程对象的start()
 *
 */
public class ThreadCreate extends Thread {
    private String name;

    public ThreadCreate(String name) {
        this.name = name;
    }

    @Override
    public void run() {//创建线程
        while (true){
            System.out.println("我是线程"+name);
            try {
                Thread.sleep(500);//线程休眠
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    public static void main(String[] args){
        ThreadCreate tc1=new ThreadCreate("线程1");//创建线程
        ThreadCreate tc2=new ThreadCreate("线程2");//创建线程
        tc1.start();
        tc2.start();
        //实现runnable接口
        MyRun mr1=new MyRun();
        MyRun mr2=new MyRun();
        //创建线程对象
        Thread th1=new Thread(mr1);
        Thread th2=new Thread(mr2);
        //启动线程
        th1.start();
        th2.start();
        Thread th3=new Thread(new Runnable() {//匿名内部类（只需要一个时创建匿名内部类）
            @Override
            public void run() {
                while (true){
                    System.out.println("我是通过匿名内部类创建的线程");
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        th3.start();
        while (true){
            System.out.println("我是主线程！");
            try {
                Thread.sleep(500);//线程休眠
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
class MyRun implements Runnable{//实现类
    @Override
    public void run() {
        while (true){
            System.out.println("我是线程"+Thread.currentThread().getName());
            try {
                Thread.sleep(500);//线程休眠
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}